package com.runfast.paotui.service.impl;

import com.runfast.common.exception.BaseException;
import com.runfast.common.service.BaseService;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.dao.model.Account;
import com.runfast.paotui.dao.model.AccountExample;
import com.runfast.paotui.dao.model.RunfastCuser;
import com.runfast.paotui.dao.model.RunfastCuserExample;
import com.runfast.paotui.service.AccountService;
import com.runfast.paotui.service.RunfastCuserService;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl extends BaseService<Account, Integer, AccountExample> implements AccountService {
    @Autowired
    private RunfastCuserService runfastCuserService;

    @Override
    public Account login(String username, String password) {
        Validate.notBlank(username);
        Validate.notBlank(password);

        AccountExample accountExample = new AccountExample();
        accountExample.createCriteria().andUsernameEqualTo(username);
        List<Account> accounts = this.selectByExample(accountExample);


        RunfastCuserExample runfastCuserExample = new RunfastCuserExample();
        runfastCuserExample.createCriteria().andMobileEqualTo(username).andPasswordEqualTo(password);
        List<RunfastCuser> runfastCusers = runfastCuserService.selectByExample(runfastCuserExample);

        if (accounts.size() == 0) throw new BaseException(ResultCode.ACCOUNT_NOT_EXIST);


        Account account = accounts.get(0);

        if (!account.getPassword().equalsIgnoreCase(password))
            throw new BaseException(ResultCode.ACCOUNT_USERNAME_OR_PASSWORD_ERROR);

        return account;
    }
}